import { configureStore, ThunkAction, Action, combineReducers } from '@reduxjs/toolkit';

import counterReducer from '../features/counter/counterSlice';
import cartReducer from '../features/cart';
import userReducer from '../features/user'
import logger from 'redux-logger'

// 持久化插件
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
// 配置
const persistConfig = {
  key: 'root',
  storage,
  // 存 模块  
  whitelist: ['user', 'cart']
}
// 合并 reducer
const rootReducer = combineReducers({
  counter: counterReducer,
  cart: cartReducer,
  user: userReducer
})
// 创建 reducer
const persistedReducer = persistReducer(persistConfig, rootReducer)

// 创建仓库
export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware({
    serializableCheck: false,
  }).concat(logger),
});
// 持久化仓库
export const persistor = persistStore(store)

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;
